<template>
  <div class="jobs-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">职位管理</h1>
        <p class="page-desc">管理企业发布的所有职位信息</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleCreateJob">
          <el-icon>
            <Plus />
          </el-icon>
          发布职位
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="职位名称">
          <el-input v-model="searchForm.title" placeholder="请输入职位名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="searchForm.department" placeholder="请选择部门" clearable style="width: 150px">
            <el-option v-for="dept in departmentOptions" :key="dept.value" :label="dept.label" :value="dept.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作地点">
          <el-select v-model="searchForm.location" placeholder="请选择地点" clearable style="width: 120px">
            <el-option v-for="location in locationOptions" :key="location.value" :label="location.label"
              :value="location.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作类型">
          <el-select v-model="searchForm.employmentType" placeholder="请选择类型" clearable style="width: 120px">
            <el-option label="全职" value="full_time" />
            <el-option label="兼职" value="part_time" />
            <el-option label="实习" value="intern" />
            <el-option label="合同工" value="contract" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="草稿" value="draft" />
            <el-option label="招聘中" value="open" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 职位列表 -->
    <el-card class="table-card">
      <!-- 批量操作工具栏 -->
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-checkbox v-model="selectAll" :indeterminate="isIndeterminate" @change="handleSelectAll">
            全选
          </el-checkbox>
          <span class="selected-count">已选择 {{ selectedJobs.length }} 项</span>
        </div>
        <div class="toolbar-right">
          <el-button type="primary" :disabled="selectedJobs.length === 0" @click="handleBatchPublish">
            批量发布
          </el-button>
          <el-button type="warning" :disabled="selectedJobs.length === 0" @click="handleBatchClose">
            批量下架
          </el-button>
          <el-button type="danger" :disabled="selectedJobs.length === 0" @click="handleBatchDelete">
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 职位表格 -->
      <el-table :data="tableData" v-loading="loading" stripe style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="55" />

        <el-table-column prop="id" label="ID" width="80" />

        <!-- 职位信息列 -->
        <el-table-column label="职位信息" min-width="250">
          <template #default="{ row }">
            <div class="job-info">
              <div class="job-title">
                <el-link type="primary" @click="handleViewJob(row)">
                  {{ row.title }}
                </el-link>
                <template v-if="row.tags">
                  <el-tag v-for="tag in parseJobTags(row.tags)" :key="tag" size="small" class="job-tag">
                    {{ tag }}
                  </el-tag>
                </template>

              </div>
              <div class="job-meta">
                <span class="department">{{ row.department }}</span>
                <el-divider direction="vertical" />
                <span class="location">{{ row.location }}</span>
                <el-divider direction="vertical" />
                <span class="employment-type">{{ getEmploymentTypeName(row.employmentType) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 薪资范围列 -->
        <el-table-column label="薪资范围" width="150">
          <template #default="{ row }">
            <div class="salary-range">
              {{ formatSalaryRange(row.salaryMin, row.salaryMax, row.currency) }}
            </div>
          </template>
        </el-table-column>

        <!-- 经验要求列 -->
        <el-table-column prop="seniority" label="经验要求" width="100">
          <template #default="{ row }">
            {{ getSeniorityName(row.seniority) }}
          </template>
        </el-table-column>

        <!-- 学历要求列 -->
        <el-table-column prop="education" label="学历要求" width="100">
          <template #default="{ row }">
            {{ getEducationName(row.education) }}
          </template>
        </el-table-column>

        <!-- 负责人列 -->
        <el-table-column label="负责人" width="120">
          <template #default="{ row }">
            <div class="owner-info">
              <el-avatar :size="24" :src="row.ownerAvatar">
                <el-icon>
                  <User />
                </el-icon>
              </el-avatar>
              <span class="owner-name">{{ row.ownerName }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 统计信息列 -->
        <el-table-column label="统计" width="120">
          <template #default="{ row }">
            <div class="job-stats">
              <div class="stat-item">
                <el-icon>
                  <View />
                </el-icon>
                <span>{{ row.viewsCount || 0 }}</span>
              </div>
              <div class="stat-item">
                <el-icon>
                  <Document />
                </el-icon>
                <span>{{ row.applicationsCount || 0 }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 状态列 -->
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 创建时间列 -->
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewJob(row)">
              <el-icon>
                <View />
              </el-icon>
              查看
            </el-button>
            <el-button type="primary" link @click="handleEditJob(row)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-dropdown style="margin-top: 3px;margin-left: 8px;"
              @command="(command: any) => handleJobAction(command, row)">
              <el-button type="primary" link>
                更多
                <el-icon>
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="row.status === 'draft'" command="publish">
                    <el-icon>
                      <Upload />
                    </el-icon>
                    发布
                  </el-dropdown-item>
                  <el-dropdown-item v-if="row.status === 'open'" command="close">
                    <el-icon>
                      <Download />
                    </el-icon>
                    下架
                  </el-dropdown-item>
                  <el-dropdown-item v-if="row.status === 'closed'" command="reopen">
                    <el-icon>
                      <Upload />
                    </el-icon>
                    重新发布
                  </el-dropdown-item>
                  <el-dropdown-item command="copy">
                    <el-icon>
                      <CopyDocument />
                    </el-icon>
                    复制
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    <el-icon>
                      <Delete />
                    </el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  User,
  View,
  Document,
  Edit,
  ArrowDown,
  Upload,
  Download,
  CopyDocument,
  Delete
} from '@element-plus/icons-vue'
import usePageState from './hooks/usePageState'
import type { JobBase } from '@/types'

// 路由实例
const router = useRouter()
const {
  loading,
  selectAll,
  selectedJobs,
  searchForm,
  pagination,
  departmentOptions,
  locationOptions,
  tableData
} = usePageState()


// 计算属性
const isIndeterminate = computed(() => {
  const selectedCount = selectedJobs.value.length
  const totalCount = tableData.value.length
  return selectedCount > 0 && selectedCount < totalCount
})

// 工具函数
/**
 * 解析职位标签
 */
const parseJobTags = (tags: string) => {
  if (!tags) return []
  return tags.split(',').map(tag => tag.trim()).filter(tag => tag)
}

/**
 * 获取工作类型名称
 */
const getEmploymentTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    'full_time': '全职',
    'part_time': '兼职',
    'intern': '实习',
    'contract': '合同工'
  }
  return typeMap[type] || type
}

/**
 * 获取经验要求名称
 */
const getSeniorityName = (seniority: string) => {
  const seniorityMap: Record<string, string> = {
    'junior': '初级',
    'mid': '中级',
    'senior': '高级'
  }
  return seniorityMap[seniority] || seniority
}

/**
 * 获取学历要求名称
 */
const getEducationName = (education: string) => {
  const educationMap: Record<string, string> = {
    'bachelor': '本科',
    'master': '硕士',
    'phd': '博士',
    'none': '不限'
  }
  return educationMap[education] || education
}

/**
 * 格式化薪资范围
 */
const formatSalaryRange = (min: number, max: number, currency: string) => {
  console.log(min, max, currency)
  if (!min && !max) return '面议'

  const formatNumber = (num: number) => {
    if (num >= 10000) {
      return (num / 1000).toFixed(0) + 'K'
    }
    return num.toString()
  }

  if (min && max) {
    return `${formatNumber(min)}-${formatNumber(max)}`
  } else if (min) {
    return `${formatNumber(min)}+`
  } else {
    return `${formatNumber(max)}以下`
  }
}

/**
 * 获取状态名称
 */
const getStatusName = (status: string) => {
  const statusMap: Record<string, string> = {
    'draft': '草稿',
    'open': '招聘中',
    'closed': '已关闭'
  }
  return statusMap[status] || status
}

/**
 * 获取状态标签类型
 */
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    'draft': 'info',
    'open': 'success',
    'closed': 'danger'
  }
  return typeMap[status] || 'info'
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 事件处理函数
/**
 * 处理搜索
 */
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

/**
 * 处理重置
 */
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    department: '',
    location: '',
    employmentType: '',
    status: ''
  })
  handleSearch()
}

/**
 * 处理创建职位
 */
const handleCreateJob = () => {
  router.push('/enterprise/jobs/create')
}

/**
 * 处理查看职位
 */

const handleViewJob = (row: JobBase) => {
  router.push(`/enterprise/jobs/${row.id}`)
}

/**
 * 处理编辑职位
 */

const handleEditJob = (row: JobBase) => {
  router.push(`/enterprise/jobs/${row.id}/edit`)
}

/**
 * 处理职位操作
 */

const handleJobAction = async (command: string, row: JobBase) => {
  switch (command) {
    case 'publish':
      await handlePublishJob(row)
      break
    case 'close':
      await handleCloseJob(row)
      break
    case 'reopen':
      await handleReopenJob(row)
      break
    case 'copy':
      await handleCopyJob(row)
      break
    case 'delete':
      await handleDeleteJob(row)
      break
  }
}

/**
 * 发布职位
 */

const handlePublishJob = async (row: JobBase) => {
  try {
    await ElMessageBox.confirm(
      `确定要发布职位「${row.title}」吗？`,
      '确认发布',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // TODO: 调用发布API
    row.status = 'open'
    ElMessage.success('职位发布成功')
  } catch {
    // 用户取消操作
  }
}

/**
 * 下架职位
 */

const handleCloseJob = async (row: JobBase) => {
  try {
    await ElMessageBox.confirm(
      `确定要下架职位「${row.title}」吗？`,
      '确认下架',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // TODO: 调用下架API
    row.status = 'closed'
    ElMessage.success('职位下架成功')
  } catch {
    // 用户取消操作
  }
}

/**
 * 重新发布职位
 */

const handleReopenJob = async (row: JobBase) => {
  try {
    await ElMessageBox.confirm(
      `确定要重新发布职位「${row.title}」吗？`,
      '确认重新发布',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // TODO: 调用重新发布API
    row.status = 'open'
    ElMessage.success('职位重新发布成功')
  } catch {
    // 用户取消操作
  }
}

/**
 * 复制职位
 */

const handleCopyJob = async (row: JobBase) => {
  try {
    // TODO: 调用复制API
    ElMessage.success(`职位「${row.title}」复制成功`)
    loadData() // 重新加载数据
  } catch (error) {
    console.error(error)
    ElMessage.error('复制失败')
  }
}

/**
 * 删除职位
 */
const handleDeleteJob = async (row: JobBase) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除职位「${row.title}」吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    // TODO: 调用删除API
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
    }
    ElMessage.success('职位删除成功')
  } catch {
    // 用户取消操作
  }
}

/**
 * 处理全选
 */
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedJobs.value = [...tableData.value]
  } else {
    selectedJobs.value = []
  }
}

/**
 * 处理选择变化
 */

const handleSelectionChange = (selection: Partial<JobBase>[]) => {
  selectedJobs.value = selection
  selectAll.value = selection.length === tableData.value.length
}

/**
 * 批量发布
 */
const handleBatchPublish = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要发布选中的 ${selectedJobs.value.length} 个职位吗？`,
      '确认批量发布',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // TODO: 调用批量发布API
    selectedJobs.value.forEach(job => {
      if (job.status === 'draft') {
        job.status = 'open'
      }
    })

    ElMessage.success('批量发布成功')
    selectedJobs.value = []
    selectAll.value = false
  } catch {
    // 用户取消操作
  }
}

/**
 * 批量下架
 */
const handleBatchClose = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要下架选中的 ${selectedJobs.value.length} 个职位吗？`,
      '确认批量下架',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // TODO: 调用批量下架API
    selectedJobs.value.forEach(job => {
      if (job.status === 'open') {
        job.status = 'closed'
      }
    })

    ElMessage.success('批量下架成功')
    selectedJobs.value = []
    selectAll.value = false
  } catch {
    // 用户取消操作
  }
}

/**
 * 批量删除
 */
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedJobs.value.length} 个职位吗？此操作不可恢复！`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    // TODO: 调用批量删除API
    const selectedIds = selectedJobs.value.map(job => job.id)
    tableData.value = tableData.value.filter(job => !selectedIds.includes(job.id))

    ElMessage.success('批量删除成功')
    selectedJobs.value = []
    selectAll.value = false
  } catch {
    // 用户取消操作
  }
}

/**
 * 处理分页大小变化
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  loadData()
}

/**
 * 处理当前页变化
 */
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

/**
 * 加载数据
 */
const loadData = () => {
  loading.value = true

  // TODO: 调用API获取数据
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.jobs-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 4px 0;
}

.page-desc {
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 16px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.selected-count {
  font-size: 14px;
  color: #909399;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.job-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.job-title {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.job-tag {
  margin-left: 4px;
}

.job-meta {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.salary-range {
  font-weight: 600;
  color: #f56c6c;
}

.owner-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.owner-name {
  font-size: 12px;
  color: #303133;
}

.job-stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }

  .header-right {
    align-self: stretch;
  }

  .table-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .toolbar-right {
    justify-content: center;
  }
}
</style>
